package com.tjc.ratelimit;

/**
 * @Author: tjc
 * @description
 * @Date Created in 0:02 2022-02-21
 * 令牌桶
 */
class TokenBucketPolicy implements RateLimitPolicy {
    private int token;
    private long createTokenRate;
    private int maxToken;
    private int initToken;
    private long maxInterval;
    private long currentTime;

    public TokenBucketPolicy(long createTokenRate, int maxToken, int initToken, long maxInterval) {
        this.createTokenRate = createTokenRate;
        this.maxToken = maxToken;
        this.initToken = initToken;
        this.maxInterval = maxInterval;
        this.currentTime = System.currentTimeMillis();
    }

    @Override
    public synchronized boolean access(String serviceName) {
        long reqMillis = System.currentTimeMillis();
        putToken(reqMillis);
        return getToken(1);
    }

    private boolean getToken(int num) {
        if (token > num) {
            token -= num;
            return true;
        }
        return false;
    }

    private void putToken(long reqMillis) {
        long t = reqMillis - currentTime;
        if (t > maxInterval) {
            token = initToken;
        } else {
            int i = (int) (t / createTokenRate);
            token += i;
            if (token > maxToken) token = maxToken;
        }
    }

}
